import 'dart:convert';
import 'dart:math';
import 'package:flutter_easyloading/flutter_easyloading.dart';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:gameplay_flutter/lib_basemodel/discover/comment_entity.dart';
import 'package:gameplay_flutter/lib_basemodel/discover/moment_entity.dart';
import 'package:gameplay_flutter/lib_baseview/widget/dialogs.dart';
import 'package:gameplay_flutter/lib_im/index.dart';
import 'package:gameplay_flutter/lib_runtime/event_bus.dart';
import 'package:gameplay_flutter/lib_runtime/event_center.dart';
import 'package:gameplay_flutter/lib_runtime/event_constant.dart';
import 'package:gameplay_flutter/lib_runtime/utils/map_util.dart';
import 'package:gameplay_flutter/m_discover/sel_friend/sel_friend_view.dart';
import 'package:get/get.dart';
import 'package:ones/extension/common.dart';
import 'package:rich_text_controllerx/rich_text_controllerx.dart';

import '../../lib_network/http_api.dart';
import '../../lib_network/http_helper.dart';
import '../../m_me/user_details_page/user_details_page.dart';
import '../../resource/language/generated/l10n.dart';
import '../post/model/at_user_model.dart';
import '../post/post_logic.dart';

class PostDetailLogic extends GetxController {
  var moment = (Get.arguments["moment"] as MomentEntity).obs;
  var comments = <CommentEntity>[].obs;

  var previewText = "";
  var hintText = T.current.discover3_say_something.obs;
  var targetComment = CommentEntity().obs;
  int? commentId;
  var messageController = RichTextController(
    text: '',
    onMatch: (match) {
      // print("match.first ${match.first} ${match}");
    },
    targets: [
      MatchTargetItem.regex(
        RegExp(r'(^|\s)@([\S]+([^\s]))', unicode: true),
        style: const TextStyle(color: Color(0xff8A72FE), fontWeight: FontWeight.bold),
      ),
    ],
  );
  var scrollController = ScrollController();
  var messageFocus = FocusNode();
  var currentIndex = 0.obs;

  var atUsers = <FriendModel>[].obs;
  var toSendComment = <ATUserModel>[].obs;

  bool get _isBottomReached {
    return scrollController.position.pixels >= scrollController.position.maxScrollExtent;
  }

  Worker? worker;
  var showEmojiView = false.obs;
  var showSendButton = false.obs;
  var sendEnable = false.obs;

  var imageHeight = 512.0.obs;

  @override
  void onInit() {
    EasyLoading.show(maskType: EasyLoadingMaskType.clear);
    if (moment().files.any((element) => element.height == 0 || element.width == 0)) {
    } else {
      var tHeight = 0.0;
      for (var e in moment().files) {
        var h = MediaQuery.of(Get.context!).size.width * (e.height / e.width);
        if (h > tHeight) tHeight = h;
      }
      imageHeight(min(tHeight, 512));
    }
    messageController.addListener(
      () {
        if (messageController.text.isNotEmpty) {
          sendEnable(true);
        } else {
          sendEnable(false);
        }

        TextControlUtils.setSpaceTextControl(messageController);
      },
    );

    discoverDynamicFind();
    discoverCommentList();
    // fetchNearbyPlaces();
    messageFocus.addListener(
      () {
        if (messageFocus.hasFocus) {
          showEmojiView(false);
          showSendButton(true);
        } else {
          showSendButton(false);
        }
      },
    );
    super.onInit();
  }

  @override
  void onClose() {
    worker?.dispose();
    messageController.dispose();
    scrollController.dispose();
    messageFocus.dispose();
    super.onClose();
  }

  discoverDynamicFind() async {
    var res = await HttpHelper.instance().post(
      HttpApi.discoverDynamicFind,
      body: {"dynamicId": moment().id},
      showLoading: true,
      showToast: true,
    );

    if (!res.isSuccess) {
      showToast(T.current.discover9_delete);
      moment(MomentEntity());
      Get.back();
      return;
    }

    moment(MomentEntity.fromJson(res.result));

    if (moment().files.any((element) => element.height == 0 || element.width == 0)) {
    } else {
      var tHeight = 0.0;
      for (var e in moment().files) {
        var h = MediaQuery.of(Get.context!).size.width * (e.height / e.width);
        if (h > tHeight) tHeight = h;
      }
      imageHeight(min(tHeight, 512));
    }

    print("moment files  ${moment().files}");
  }

  discoverCommentList() async {
    var res = await HttpHelper.instance().post(
      HttpApi.discoverCommentList,
      body: {"dynamicId": moment().id, "pageNum": 1, "pageSize": 100},
      showLoading: true,
      showToast: true,
    );
    comments.assignAll((res.result["list"] as List?)?.map((e) => CommentEntity.fromJson(e)) ?? []);
  }

  discoverComment() async {
    if (!sendEnable()) return;
    if (messageController.text.isEmpty) return;

    messageFocus.unfocus();
    print(json.encode(convertStringToATUserModels(messageController.text, atUsers())));
    // return;
    var contents = json.encode(convertStringToATUserModels(messageController.text, atUsers()));

    var res = await HttpHelper.instance().post(
      HttpApi.discoverComment,
      body: {"dynamicId": moment().id, if (commentId != null) "commentId": commentId, "contentInfoListStr": contents},
      showLoading: true,
      showToast: true,
    );
    messageController.text = "";
    messageFocus.unfocus();
    atUsers.clear();
    discoverCommentList();
    discoverDynamicFind();
  }

  like() async {
    var isLike = moment().isLike;
    moment.update(
      (val) {
        if (isLike) {
          val?.likes -= 1;
        } else {
          val?.likes += 1;
        }
        val?.isLike = val.isLike.not();
      },
    );
    var res = await HttpHelper.instance().post(
      HttpApi.discoverLike,
      showLoading: true,
      body: {"dynamicId": moment().id, "status": isLike ? 0 : 1},
      showToast: true,
    );
    eventBus.fire(isLike ? UnLikeAction(moment()) : LikeAction(moment()));
  }

  likeComment(CommentEntity comment) async {
    var res = await HttpHelper.instance().post(
      HttpApi.discoverLikeComment,
      body: {"commentId": comment.id, "status": comment.isLike == 1 ? 0 : 1},
      showLoading: false,
      showToast: true,
    );
    discoverCommentList();
  }

  attention() async {
    debugPrint("isAttention: ${moment().isAttention}");
    var res = await HttpHelper.instance().post(
      HttpApi.discoverAttention,
      body: {"isAttention": moment().isAttention == 1 ? 0 : 1, "toUserId": moment().userId},
      showLoading: false,
      showToast: true,
    );
    eventBus.fire(FollowUserAction());
    moment.update(
      (val) {
        val?.isAttention = val.isAttention == 1 ? 0 : 1;
      },
    );
  }

  deleteComment(int id) async {
    var res = await HttpHelper.instance().post(
      HttpApi.discoverDeleteComment,
      body: {"id": id},
      showLoading: true,
      showToast: true,
    );
    discoverCommentList();
    // comments.assignAll((res.result as List).map((e) => MomentEntity.fromJson(e)));
  }

  clickComment() async {
    if (_isBottomReached) {
      commentId = null;
      _openKeyboard();
    } else {
      scrollController.animateTo(
        scrollController.position.maxScrollExtent,
        duration: const Duration(milliseconds: 160),
        curve: Curves.easeInOut,
      );
    }
  }

  void _openKeyboard() {
    FocusScope.of(Get.context!).requestFocus(messageFocus); // 请求焦点
  }

  atUser() async {
    var user = await Get.to(() => SelFriendPage());
    if (user is FriendModel) {
      atUsers.add(user);
      var mText = messageController.text;
      if (mText.endsWith(' @')) {
        messageController.text = "$mText${user.nickname} ";
      } else {
        messageController.text = "$mText @${user.nickname} ";
      }
    }
  }

  fetchNearbyPlaces() async {
    var res = await GoogleMapUtils.fetchNearbyPlaces();
    debugPrint("fetchNearbyPlaces ${res.toString()}");
  }
}
